import type { ElementSelectors } from '../../lib/abstract'
import type {
  ComponentStyleIdType,
  ECElementEvent,
  ECharts,
  EChartsOption,
  EchartsTitleOption,
} from '../../types/interfaces'
import type { BarChartProps } from './types'
import { UIComponent } from '../../lib/abstract'
import {
  ComponentStyleId,
  DEFAULT_ECHARTS_TITLE_TEXT_STYLE,
  logger,
} from '../../types/constants'
import { SYMBOLS } from '../../types/interfaces'
import { styles } from './styles'
import { DEFAULT_BAR_CHART_PROPS } from './types'

export class BarChart extends UIComponent<BarChartProps> {
  id: string = 'bar-chart'
  readonly description: string = '柱状图组件'
  readonly styleId: string = ComponentStyleId[this.name]
  private chartInstance: ECharts | null = null
  private resizeObserver: ResizeObserver | null = null

  get name(): ComponentStyleIdType {
    return 'BarChart'
  }

  get className(): string {
    return 'custom-bar-chart'
  }

  constructor(props: BarChartProps) {
    super({
      ...DEFAULT_BAR_CHART_PROPS,
      ...props,
    })

    this.registerStyles()
  }

  ELEMENT_SELECTORS: ElementSelectors = {

  }

  /**
   * 初始化图表
   * @private
   */
  private initChart(): void {
    if (!this.props.id) {
      logger.error(`[${this.name}] 容器 id 不能为空`)
      return
    }

    const container = document.getElementById(this.props.id)

    if (!container) {
      logger.error(`[${this.name}] 容器 id 为 ${this.props.id} 的元素不存在`)
      return
    }

    this.chartInstance = echarts.init(container)
    this.updateChart()

    // 添加响应式处理
    this.resizeObserver = new ResizeObserver(() => {
      this.chartInstance?.resize()
    })
    this.resizeObserver.observe(container)
  }

  /**
   * 更新图表配置
   * @private
   */
  private updateChart(): void {
    if (!this.chartInstance)
      return

    const { title, titleOptions, categories, values, options } = this.props

    // 计算最佳配置
    const chartConfig = this.calculateOptimalChartConfig(categories)

    const defaultOptions: EChartsOption = {
      // 添加标题配置
      title: titleOptions || (title
        ? {
            text: title,
            textStyle: DEFAULT_ECHARTS_TITLE_TEXT_STYLE,
          } as EchartsTitleOption
        : undefined),
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
        formatter: (params: any) => {
          const data = params[0]
          return `${data.name}<br/>数量: ${data.value}`
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%', // 为 x 轴标签留更多空间
        top: title ? '20%' : '10%', // 根据是否有标题调整顶部间距
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        data: categories,
        axisLabel: {
          interval: 0, // 强制显示所有标签
          rotate: chartConfig.labelRotation, // 标签旋转角度
          // width: chartConfig.labelWidth, // 标签最大宽度
          lineHeight: 18,
          formatter: (value: string) => {
            // 处理换行显示
            return value.replace(/\n/g, '\n') // 确保换行符被正确解析
          },
          overflow: 'truncate', // 超出截断
          ellipsis: '...', // 截断显示省略号
        },
        axisTick: {
          alignWithLabel: true,
        },
      },
      yAxis: {
        type: 'value',
        min: 0, // 确保y轴从0开始，避免图表顶部有空白
        splitLine: {
          show: true, // 显示网格线
        },
      },
      series: [{
        name: '数量',
        type: 'bar',
        data: values,
        barWidth: '30%', // 控制柱状宽度
        itemStyle: {
          color: (params: any) => {
            // 为0的数据使用不同颜色
            return params.value === 0 ? '#999' : '#5470C6'
          },
        },
        label: {
          show: true,
          color: '#1E90FF',
          position: 'top',
          formatter: (params: any) => {
            return params.value === 0 ? '0' : params.value
          },
        },
        ...this.props.seriesOptions,
      }],
      ...options, // 允许外部覆盖默认配置
    }

    this.chartInstance.setOption(defaultOptions)
  }

  /**
   * 计算最佳图表配置
   */
  private calculateOptimalChartConfig(categories: string[]): {
    gridBottom: string
    gridTop: string
    gridLeft: string
    gridRight: string
    labelRotation: number
    labelWidth: number
    maxLabelLength: number
    barWidth: string
  } {
    const { title } = this.props

    // 分析标签长度
    const maxLabelLength = Math.max(...categories.map(label => label.length))
    const totalLabels = categories.length

    // 根据标签长度和数量计算旋转角度
    let labelRotation = 0
    let gridBottom = '15%'
    let labelWidth = 100
    let maxLabelLengthThreshold = 30

    if ((maxLabelLength > 15 && totalLabels > 1) || totalLabels > 8) {
      labelRotation = 45
      gridBottom = '25%'
      labelWidth = 80
      maxLabelLengthThreshold = 15
    }

    if ((maxLabelLength > 25 && totalLabels > 1) || totalLabels > 12) {
      labelRotation = 90
      gridBottom = '30%'
      labelWidth = 60
      maxLabelLengthThreshold = 10
    }

    // 根据数据点数量调整柱状图宽度
    let barWidth = '30%'
    if (totalLabels > 15) {
      barWidth = '20%'
    }
    else if (totalLabels > 8) {
      barWidth = '25%'
    }

    return {
      gridBottom,
      gridTop: title ? '20%' : '10%',
      gridLeft: '3%',
      gridRight: '4%',
      labelRotation,
      labelWidth,
      maxLabelLength: maxLabelLengthThreshold,
      barWidth,
    }
  }

  render(): string {
    const { id, height = '300px', width = '100%' } = this.props

    return this.isEmptyData()
      ? ''
      : `
      <div id="${id}" 
       class="${this.className}" 
       style="height: ${height}; width: ${width};">
      </div>
    `
  }

  bindEvents(): void {
    // 如果数据为空，不绑定事件
    if (this.isEmptyData()) {
      logger.notice(`[${this.name}] ${SYMBOLS.STATUS.WARNING} ${this.props.id} （${this.props.title || '柱状图'}） 数据为空，跳过生成图表`)
      return
    }

    // 图表初始化延迟到 DOM 加载完成后
    setTimeout(() => {
      this.initChart()
      this.handleChartClick()
    }, 0)
  }

  handleChartClick(): void {
    this.chartInstance?.on('click', (params: ECElementEvent) => {
      if (params.componentType === 'series' && params.seriesType === 'bar') {
        // logger.info(`[${this.name}] ${this.props.containerId} 柱状图点击事件触发`, params)

        this.props.onClick?.(
          {
            chartId: this.props.id,
            dataIndex: params.dataIndex,
            name: params.name,
            value: params.value,
            seriesName: params.seriesName,
            rawData: params.data,
          },
          params.event,
        )
      }
    })
  }

  /**
   * 刷新图表数据
   */
  refresh(categories: string[], values: number[], options?: EChartsOption): void {
    if (!this.chartInstance) {
      this.initChart()
      return
    }

    this.chartInstance.setOption({
      xAxis: {
        data: categories,
      },
      series: [{
        data: values,
        ...options?.series,
      }],
      ...options,
    })
  }

  /**
   * 检查是否为空数据
   */
  private isEmptyData(): boolean {
    const { values, renderEmpty } = this.props

    return !renderEmpty && (values.length === 0 || values.every((value: number) => value === 0))
  }

  getChartInstance(): ECharts | null {
    return this.chartInstance
  }

  getStyles(): string {
    return styles(this.className)
  }

  destroy(): void {
    super.destroy()
  }

  cleanupReferences(): void {
    this.resizeObserver?.disconnect()
    this.resizeObserver = null
    this.chartInstance?.dispose()
    this.chartInstance = null
  }
}
